const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('📝 收到施工队伍注册申请')

  try {
    // 获取用户 openid
    const { OPENID } = cloud.getWXContext()

    const {
      avatar,
      name,
      phone,
      location,
      category,
      categoryName,
      experience,
      description,
      specialties,
      certifications,
      type,
      typeName,
      serviceRegions, // 服务地区数组
      // 个人师傅特有字段
      realName,
      idCard,
      // 公司特有字段
      companyName,
      businessLicense,
      legalRepresentative,
      registeredCapital,
      companyAddress
    } = event
    
    // 数据验证
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败，请重新登录'
      }
    }

    if (!avatar || !name || !phone || !location || !category || !experience || !description) {
      return {
        success: false,
        error: '必填字段不能为空'
      }
    }
    
    // 手机号验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return {
        success: false,
        error: '手机号格式不正确'
      }
    }
    
    // 检查是否已经注册过（按 openid 检查）
    const existingByOpenid = await db.collection('construction_teams')
      .where({
        openid: OPENID
      })
      .get()

    if (existingByOpenid.data.length > 0) {
      const existingStatus = existingByOpenid.data[0].auditStatus
      if (existingStatus === 'pending') {
        return {
          success: false,
          error: '您的注册申请正在审核中，请耐心等待'
        }
      } else if (existingStatus === 'approved') {
        return {
          success: false,
          error: '您已经注册并通过审核'
        }
      } else if (existingStatus === 'rejected') {
        return {
          success: false,
          error: '您的注册申请已被拒绝，如有疑问请联系客服'
        }
      }
    }

    // 检查手机号是否被其他用户使用
    const existingByPhone = await db.collection('construction_teams')
      .where({
        phone: phone,
        openid: db.command.neq(OPENID) // 排除当前用户
      })
      .get()

    if (existingByPhone.data.length > 0) {
      return {
        success: false,
        error: '该手机号已被其他用户注册'
      }
    }
    
    // 生成唯一ID
    const registrationId = `reg_${Date.now()}_${Math.floor(Math.random() * 1000)}`
    
    // 准备注册数据
    const registrationData = {
      id: registrationId,
      openid: OPENID, // 用户 openid
      avatar,
      name,
      phone,
      location,
      category,
      categoryName,
      experience,
      description,
      specialties: Array.isArray(specialties) ? specialties : [],
      certifications: Array.isArray(certifications) ? certifications : [],
      serviceRegions: Array.isArray(serviceRegions) ? serviceRegions : [], // 服务地区数组
      type,
      typeName,
      // 审核相关字段
      auditStatus: 'pending', // 审核状态：pending(待审核)、approved(已通过)、rejected(已拒绝)
      canReceiveOrders: false, // 是否可以接单
      auditTime: null, // 审核时间
      auditReason: '', // 审核备注
      auditBy: '', // 审核人
      // 业务相关字段
      rating: 0,
      completedProjects: 0,
      status: 'available', // 工作状态：available(可接单)、busy(忙碌中)
      joinDate: new Date().toISOString().split('T')[0],
      tags: [],
      priceRange: '', // 价格范围
      submitTime: new Date(),
      createTime: new Date(),
      updateTime: new Date()
    }
    
    // 添加类型特有字段
    if (type === 'individual') {
      registrationData.realName = realName || name
      registrationData.idCard = idCard || ''
    } else if (type === 'company') {
      registrationData.companyName = companyName || name
      registrationData.businessLicense = businessLicense || ''
      registrationData.legalRepresentative = legalRepresentative || ''
      registrationData.registeredCapital = registeredCapital || ''
      registrationData.companyAddress = companyAddress || location
    }
    
    // 插入到施工队伍集合（待审核状态）
    const insertResult = await db.collection('construction_teams').add({
      data: registrationData
    })
    
    console.log('✅ 注册申请提交成功:', insertResult._id)
    
    // 发送通知（可选）
    try {
      await this.sendNotification(registrationData)
    } catch (notifyError) {
      console.warn('⚠️ 发送通知失败:', notifyError)
      // 通知失败不影响注册申请的成功
    }
    
    return {
      success: true,
      message: '注册申请提交成功',
      data: {
        registrationId: registrationId,
        insertId: insertResult._id,
        status: 'pending'
      }
    }
    
  } catch (error) {
    console.error('❌ 注册申请提交失败:', error)
    return {
      success: false,
      error: error.message || '提交失败，请重试'
    }
  }
}

// 发送通知（管理员通知）
async function sendNotification(registrationData) {
  console.log('📧 发送注册申请通知')
  
  try {
    // 这里可以添加发送邮件、短信或其他通知方式
    // 例如：发送给管理员的通知
    
    const notificationData = {
      type: 'team_registration',
      title: '新的施工队伍注册申请',
      content: `${registrationData.typeName} "${registrationData.name}" 提交了注册申请`,
      data: {
        registrationId: registrationData.id,
        applicantName: registrationData.name,
        applicantPhone: registrationData.phone,
        applicantType: registrationData.typeName,
        submitTime: registrationData.submitTime
      },
      createTime: new Date()
    }
    
    // 插入通知记录
    await db.collection('admin_notifications').add({
      data: notificationData
    })
    
    console.log('✅ 通知发送成功')
    
  } catch (error) {
    console.error('❌ 发送通知失败:', error)
    throw error
  }
}
